// MyException.cpp: implementation of the CMyException class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "8085.h"
#include "MyException.h"
#include "GlobalFunctions.h"

#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

CMyException::CMyException()
{
    Init();
    SetSeverity(noerror);
    m_szErrorMsg = "No Error";
    FindLineAndColumn();
}

CMyException::CMyException(severity s,the_exceptions e, CString str)
{
    Init();
    Set(s,e);
    m_szErrorMsg = str;
    FindLineAndColumn();
}

// use this to include line number while displaying error messages
CMyException::~CMyException()
{

}

void CMyException::Set(severity s, the_exceptions e)
{
    SetSeverity(s);
    SetException(e);
}

void CMyException::Set(severity s, the_exceptions e,CString str)
{
    SetSeverity(s);
    SetException(e);
    SetErrorMessage(str);
}

void CMyException::SetSeverity(severity s)
{
    m_severity = s;
    m_nExceptionOccured = s==noerror ? 0 : 1;
}

void CMyException::SetException(the_exceptions e)
{
    m_exception = e;
}

void CMyException::SetErrorMessage(CString errMsg)
{
    m_szErrorMsg = errMsg;
}

CString & CMyException::GetErrorMessage()
{
    return m_szErrorMsg;
}


void CMyException::Init()
{
    m_nLine = m_nColumn = -1;
}

// try to extract the line and columne number from the message string
void CMyException::FindLineAndColumn()
{
    if(m_szErrorMsg.IsEmpty()) return;
    int nRet;
    char *szLine="Line",*szCol="Column";
    char *str = new char[m_szErrorMsg.GetLength()+1];
    strcpy(str,m_szErrorMsg);

    // extract the digits after the string 'Line'
    if((nRet=m_szErrorMsg.Find(szLine,0))!=-1)
        m_nLine = ExtractNumber(&str[nRet+strlen(szLine)],10);

    // extract the digits after the string 'Column'
    if((nRet=m_szErrorMsg.Find(szCol,0))!=-1)
        m_nColumn = ExtractNumber(&str[nRet+strlen(szCol)],10);
    delete [] str;
}

int CMyException::ExtractNumber(char *str, int nBase)
{
    for(int i=0; i<strlen(str) ; i++)
        if(isdigit(str[i]))
        {
            char *end;
            return strtol(&str[i],&end,nBase);
        }
        return 0;
}

int CMyException::GetLineNumber()
{
    return m_nLine;
}

int CMyException::GetColumn()
{
    return m_nColumn;
}

// returns true if the the_exceptions occured due to a breakpoint
BOOL CMyException::IsBreakPoint()
{
    return m_exception==breakpoint;
}

BOOL CMyException::IsRetExecuted()
{
    return m_exception==ret_executed;
}

void CMyException::ShowErrorMessage()
{
    ::ShowErrorMessage((LPCTSTR )m_szErrorMsg);
}
